package cn.jinjimi.app.webview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Locale;

import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.webview.event.ReqRouteUrlEvent;
import cn.jinjimi.app.webview.utils.BaseWebViewClient;
import cn.jinjimi.app.webview.utils.WebUtils;
import cn.jinjimi.app.webview.utils.InterceptResponse;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.Scheme;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.URLUtil;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.framework.router.RouterHelper;

/**
 * @author zhenhua
 */
public class WebViewHelper {

    private static final String USER_AGENT = ";JJM(Version %s;Build %s;Android %s)";

    public static String getUserAgent(Context context) {
        return String.format(Locale.CHINA, USER_AGENT,
                AndroidUtils.getAppVersionName(context)
                , AndroidUtils.getAppVersionCode(context)
                , AndroidUtils.getSystemVersionName());
    }

    /**
     * 设置WebView
     */
    public static void setUpWebView(Activity activity, WebView webView) {
        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);

        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + getUserAgent(activity));
        webView.getSettings().setUseWideViewPort(true);
        // It must open.
        // This WebView support some native APIs.
        webView.getSettings().setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient(activity));
    }

    public static class WebViewClient extends BaseWebViewClient {

        WeakReference<Activity> mActivityRef;

        public WebViewClient(Activity activity) {
            mActivityRef = new WeakReference<>(activity);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //change bundle context url:
            /*NetResourceManager.getInstance().onPageStart(url);*/

            final Context context = view.getContext();

            //空URL
            if (StringUtils.isEmpty(url)) {
                return true;
            }

            //Native Link协议
            //使用本地路由打开原生界面
            if (RouterHelper.isNativeUrl(url)) {
                if (context != null) {
                    Router.create(context, url).open();
                }
                return true;
            }

            //TEL协议
            //使用本地呼叫页面打电话
            else if (url.startsWith(Scheme.TEL)) {
                if (context != null) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                    context.startActivity(intent);
                }
                return true;
            }

            //微信支付协议
            else if (url.startsWith(Constants.UriScheme.PAY_WX)) {
                if (context != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                    return true;
                }
            }

            return processAlipayProtocol(view, url)
                    || processJJMUrlProtocol(view, url)
                    || super.shouldOverrideUrlLoading(view, url);

        }

        private boolean processAlipayProtocol(final WebView view, final String url) {
            Activity activity = mActivityRef.get();
            if (activity != null) {
                return new PayTask(activity).payInterceptorWithUrl(url, true, new H5PayCallback() {
                    @Override
                    public void onPayResult(H5PayResultModel result) {
                        if (result != null) {
                            String resultCode = result.getResultCode();
                            if (TextUtils.equals("9000", resultCode)) {
                                //"支付成功"
                            } else if (TextUtils.equals("4000", resultCode) || TextUtils.equals("6002", resultCode)) {
                                //"支付失败"
                            } else if (TextUtils.equals("6001", resultCode)) {
                                //"取消支付"
                            }
                            if (!TextUtils.isEmpty(result.getReturnUrl())) {
                                EventBus.getDefault().post(new ReqRouteUrlEvent(result.getReturnUrl()));
                            }
                        }
                    }
                });
            }
            return false;
        }

        private boolean processJJMUrlProtocol(WebView view, String url) {
            //add app token
            if (WebUtils.isDomain(url)) {
                url = URLUtil.appendParam(url, Constants.ParamKey.APP_TOKEN,
                        AccountManager.getInstance().getToken());
                //open in new WebActivity
                if (url.contains(Constants.UriScheme.JJM_OPEN_IN_NEW)
                        && !url.contains("alipay.com")) {
                    RouterHelper.toUrl(view.getContext(), url);
                    return true;
                }
            }
            return false;
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            WebResourceResponse response = null;
            try {
                response = InterceptResponse.responseWithLocalFile(url);
            } catch (IOException e) {
                //
            }
            return response != null ? response : super.shouldInterceptRequest(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            WebResourceResponse response = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                try {
                    //Local Resource
                    response = InterceptResponse.responseWithLocalFile(request.getUrl());
                } catch (IOException e) {
                    //
                }
            }
            return response != null ? response : super.shouldInterceptRequest(view, request);
        }

    }

}